<template>
  <div class="login">
    <el-card class="login_center">
      <template #header>
        <div class="card_header">
          <span>用户登录</span>
        </div>
      </template>
      <el-form :model="loginFormState" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            v-model.trim="loginFormState.username"
            maxlength="32"
            placeholder="请输入账号"
            clearable
          >
            <template #prefix>
              <Icons name="User"></Icons>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input
            v-model.trim="loginFormState.pwd"
            maxlength="16"
            show-password
            placeholder="请输入密码"
            clearable
            @keyup.enter.exact="handleLogin"
          >
            <template #prefix>
              <Icons name="Lock"></Icons>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            :loading="loginFormState.loading"
            @click="handleLogin"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { encode } from "js-base64";
import Icons from "../../components/Icons.vue";
import { UserModel } from "@/model/userModel";
import { decodeParam } from "@/utils/encrypt";
import appStore from "@/store";
import permissionToken from "@/utils/permissionToken";

const store = appStore.userStore;
const { proxy } = getCurrentInstance()!;
const route = useRoute();
const router = useRouter();
const loginFormRef = ref();

const loginFormState = reactive({
  username: "admin",
  pwd: "admin",
  loading: false,
});

const rules = {
  username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  pwd: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度为5-16位", trigger: "blur" },
  ],
};

const handleLogin = () => {
  loginFormRef.value.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    loginFormState.loading = true;

    let params: UserModel = {
      userName: loginFormState.username,
    };

    setTimeout(async () => {
      let users = {
        role: loginFormState.username === "admin" ? "admin" : "user",
      };
      Object.assign(params, users);
      localStorage.setItem(
        "auth_token",
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwZXJtaXNzaW9ucyI6ImFkbWluIiwiaXNzIjoic3RlcCIsIm5hbWUiOiLlvKDkuIkxIiwiZXhwIjoxNjgxOTg2OTQxLCJ1c2VyTmFtZSI6IjE5ODQxMjQxMjIzIiwiZGVwYXJ0bWVudCI6IuawkeaUv-WxgCIsInVzZXJJZCI6IjEifQ.Y1-uxm-X64kmNHr7VbKXplqw4PWWda_nsGkTVdl4uig",
      );
      store.setUser(params);
      loginFormState.loading = false;

      if (route.query?.redirect) {
        router.replace(`${decodeParam(route.query.redirect as string)}`);
      } else {
        router.replace("/");
      }
      proxy!.$message.success("登录成功");
    }, 1000);

    // proxy.$axios
    // 	.post("/user/login", proxy.$qs.stringify(params))
    // 	.then(res => {
    // 		let { code, result_data, message } = res.data;
    // 		if (code == 1) {
    // 			console.log("login_success", result_data);
    // 			ElMessage.success("登录成功");
    // 		} else {
    // 			ElMessage.error("登录失败：" + message);
    // 		}
    // 	})
    // 	.catch(err => {
    // 		console.log("login err", err);
    // 		ElMessage.error("登录失败");
    // 	});
  });
};
</script>

<style lang="scss" scoped>
.login {
  width: 100vw;
  height: 100vh;
  background-image: url("../../assets/img/login.jpg");
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  .login_center {
    width: 396px;
    height: auto;
  }

  .card_header {
    font-size: 18px;
    text-align: center;
  }
}
</style>
